// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import path from 'path'
import type { UserConfig, PluginOption } from 'vite'
import { readFileSync } from 'fs'

export default defineConfig(({ mode }): UserConfig => {
	// 1. 加载环境变量（包含VITE_前缀的所有变量）
	const env = loadEnv(mode, process.cwd(), ['VITE_', 'APP_'])

	const pkg = JSON.parse(readFileSync('./package.json', 'utf-8'))

	console.log(env)


	// 2. 动态配置
	const plugins: PluginOption[] = [
		vue(),
		svelte({
			emitCss: false,
			compilerOptions: {
				customElement: true,
			},
		}),
	]

	// 3. 完整配置
	return {
		base: './',
		plugins,
		// 路径解析
		resolve: {
			alias: {
				'~': path.resolve(__dirname, './'),
				'@': path.resolve(__dirname, './src'),
				'#': path.resolve(__dirname, './types'),
			},
			extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue', '.svelte']
		},

		// 构建配置
		build: {
			//minify: mode === 'production' ? 'esbuild' : false,
			sourcemap: true, // 生成 sourcemap 便于调试
			target: 'esnext',
			minify: 'esbuild',
			reportCompressedSize: false,
			rollupOptions: {
				output: {
					manualChunks: undefined,
					inlineDynamicImports: true,
					assetFileNames: 'assets/[hash][extname]',
					entryFileNames: 'assets/[hash].js'
				},
				external: mode === 'production' ? [] : []
			},
			//sourcemap: mode !== 'production'
		},

		// 开发服务器
		server: {
			port: Number(env.VITE_PORT || 2803),
			host: true,
			open: true,
			proxy: {
				'/api': {
					target: env.VITE_PROXY_TARGET
						|| 'https://www.fastmock.site/mock/5039c4361c39a7e3252c5b55971f1bd3/api',
					changeOrigin: true,
					rewrite: path => path.replace(/^\/api/, ''),
					secure: false
				}
			}
		},

		// CSS处理
		css: {
			preprocessorOptions: {
				less: {
					javascriptEnabled: true,
					additionalData: `@env: "${mode}";`
				},
				scss: {
					additionalData: `$env: "${mode}";`
				}
			},
			postcss: {
				plugins: [
					{
						postcssPlugin: 'internal:charset-removal',
						AtRule: {
							charset: atRule => {
								if (atRule.name === 'charset') atRule.remove()
							}
						}
					}
				]
			}
		},

		// 环境变量全局化
		define: {
			__APP_VERSION__: JSON.stringify(pkg.version),
			__APP_ENV__: JSON.stringify({
				mode,
				buildTime: new Date().toISOString()
			}),
			// 注入 import.meta.env
			'import.meta.env': JSON.stringify(env),
			// 兼容 legacy 代码中的 process.env
			'process.env': Object.fromEntries(
				Object.entries(env).filter(([key]) => key.startsWith('VITE_') || key.startsWith('APP_'))
			),
		},

		// 优化配置
		optimizeDeps: {
			include: ['vue', 'svelte']
		}
	}
})
